geometry greedy implementation

Please click on ads to support us..

Python Code:

def eff(l):
    if l[0]>=0:
        return l[-1]
    elif l[-1]<0:
        return -l[0]
    elif l[0]<=0 and l[-1]>=0:
        return l[-1]-l[0]
    
t=int(input())
for i in range (0,t):
    x=[]
    y=[]
    n=int(input())
    ans=0
    for i1 in range (0,n):
        cx,cy=input().split()
        if int(cx)==0:
            y.append(int(cy))
        else:
            x.append(int(cx))
    x=sorted(x)
    y=sorted(y)
    if len(x)==0:
        print(2*eff(y))
    elif len(y)==0:
        print(2*eff(x))
    else:
        print(2*eff(x)+2*(eff(y)))
        
        
        

C++ Code:

/*
* @Author: gorsonpy
* @Date: 2023-02-22 17:27
* @Last Modified by: gorsonpy
* @Last Modified time: 2023-02-22 17:27
*/
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<unordered_map>
#include<queue>
#include<set>
#include<unordered_set>
#include<cmath>
using namespace std;
using PII = pair<int, int>;
using LL = long long;

#define x first
#define y second
#define endl '\n'
#define pb push_back
#define cl(a) memset(a, 0, sizeof a)
#define dbg(x) cout << x << ':' << '-' << '-' << x << endl;

const int N = 2e5 + 10, mod = 1e9 + 7; 
int T, n, m, k, q;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; 
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
void solve()
{
    cin >> n;
    int xmax = 0, ymax = 0, xmin = 0, ymin = 0;
    for(int i = 0; i < n; ++i)
    {
        int x, y;
        cin >> x >> y;
        xmax = max(xmax, x), xmin = min(x, xmin);
        ymax = max(ymax, y), ymin = min(ymin, y);
    }

    int a = xmax - xmin, b = ymax - ymin;
    cout << (a + b) * 2 << endl;
}

int main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    cin >> T;
    while(T--) solve();
    return 0;
}


Comments

Submit
0 Comments
More Questions

1217. Minimum Cost to Move Chips to The Same Position
347. Top K Frequent Elements
1503. Last Moment Before All Ants Fall Out of a Plank
430. Flatten a Multilevel Doubly Linked List
1290. Convert Binary Number in a Linked List to Integer
1525. Number of Good Ways to Split a String
72. Edit Distance
563. Binary Tree Tilt
1306. Jump Game III
236. Lowest Common Ancestor of a Binary Tree
790. Domino and Tromino Tiling
878. Nth Magical Number
2099. Find Subsequence of Length K With the Largest Sum
1608A - Find Array
416. Partition Equal Subset Sum
1446. Consecutive Characters
1618A - Polycarp and Sums of Subsequences
1618B - Missing Bigram
938. Range Sum of BST
147. Insertion Sort List
310. Minimum Height Trees
2110. Number of Smooth Descent Periods of a Stock
2109. Adding Spaces to a String
2108. Find First Palindromic String in the Array
394. Decode String
902. Numbers At Most N Given Digit Set
221. Maximal Square
1200. Minimum Absolute Difference
1619B - Squares and Cubes
1619A - Square String